const swrCache = {}; window.swrCache = swrCache;
const swrAbort = {}; window.swrAbort = swrAbort;

async function swr(fetcher, {cacheKey, cacheTime, abortKey}) {
    if(abortKey){
      let lastFetcher = swrAbort[abortKey];
      if(lastFetcher.abort){
        abort.abort();
      }
    }
  
    if(cacheKey){
      let data = swrCache[cacheKey] || { value: null, time: 0, promise: null };
      swrCache[cacheKey] = data;
      
      // 是否过期
      const isStaled = Date.now() - data.time > cacheTime;
      // 已经过期了，且也没有在请求中，需要发送请求
      if (isStaled && !data.promise) {
        data.promise = fetcher()
          .then((val) => {
            data.value = val;
            data.time = Date.now(); // 保存获取到数据的时间
          })
          .catch((err) => {
            console.log(err);
          })
          .finally(() => {
            data.promise = null;
          });
      }
      
      if (data.promise && !data.value) await data.promise;
      return data.value;
    }
  
    return fetcher;
}

export function genSwrKey(obj){
    let key = Object.keys(obj).reduce((pre,cur) => `${pre}.${cur}=${obj[cur]}`, '');
    return key
}

export {swr, genSwrKey}